package com.appbee.article.client.presenter;

import javax.inject.Inject;

import com.appbee.article.shared.ArticleProxy;
import com.appbee.article.shared.ArticleServiceRequest;
import com.appbee.user.client.AccessControl;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.web.bindery.requestfactory.shared.Receiver;

public class ArticleBoxPresenter
{
	public interface View extends IsWidget
	{

		void showContent(String content);

		void edit(String content);

		void setCanEdit(boolean canEdit);
		
		void showLoadingIndicator();

	}
	
	private View view;
	private ArticleProxy article;
	private ArticleProxy editArticle;
	private ArticleServiceRequest request;
	private final boolean canEdit;
	private boolean articleInEditMode = false;
	private final ArticleDataProvider articleDataProvider;
	
	

	@Inject
	public ArticleBoxPresenter(	ArticleDataProvider articleDataProvider,
			AccessControl accessControl)
	{
		super();
		this.articleDataProvider = articleDataProvider;
		canEdit = accessControl.isMemberOrAdmin();
	}
	
	public void setView(View view)
	{
		this.view = view;
		view.setCanEdit(canEdit);
	}
	
	public void setStrId(String strId)
	{
		view.showLoadingIndicator();
		articleDataProvider.getByStrId(strId, new Receiver<ArticleProxy>()
		{

			@Override
			public void onSuccess(ArticleProxy response)
			{
				article = response;
				view.showContent(article.getContent());
						articleInEditMode = false;
			}
			
		});
	}
	
	public void onEdit()
	{
		if (!articleInEditMode)
		{
			request = articleDataProvider.getArticleRequestFactory()
					.getArticleService();
			editArticle = request.edit(article);
			articleInEditMode = true;
		}
		view.edit(article.getContent());
	}
	
	public void onSave(String content)
	{
		if (!articleInEditMode)
			return;

		articleInEditMode = false;
		if (content.equals(article.getContent()))
		{
			view.showContent(article.getContent());
			return;
		}
		editArticle.setContent(content);
		request.save(editArticle).fire(new Receiver<ArticleProxy>()
		{

			@Override
			public void onSuccess(ArticleProxy response)
			{
				article = response;
				view.showContent(article.getContent());
			}
			
		});
	}

	public void onCancel()
	{
		view.showContent(article.getContent());
	}
	
	
}
